<?php

namespace app\console\controller;

use app\common\service\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class GroupChatLog extends Command
{
    protected function configure()
    {
        $this->setName('chatlog:group')->setDescription('run chatlog of group to db');
    }

    protected function execute(Input $input, Output $output)
    {
        $yesterday = strtotime(date('Y-m-d')) - 1;
        $redis = new Redis();
        $keys = $redis->keys('rec:group:*');
        foreach ($keys as $key) {
            $contents = $redis->zRangeByScore($key, 0, $yesterday);
            $group_chat_log = [];
            foreach ($contents as $i=>$content){
                $content = json_decode($content,true);
                $group_chat_log[$i]['send_uid'] = $content['mine']['id'];
                $group_chat_log[$i]['receive_gid'] = $content['to']['id'];
                $group_chat_log[$i]['send_content'] = $content['mine']['content'];
                $group_chat_log[$i]['send_time'] = round($content['to']['timestamp']/1000);
            }
            $re = model('common/groupChatLog')->saveAll($group_chat_log);
            if($re){
                $redis->zRemRangeByScore($key, 0, $yesterday);
            }
        }
    }
}